package com.ruoyi.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysRoleDept;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.GetDingAllDeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import com.ruoyi.asms.service.IAsmsAssetFullInfoService;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description
 * @Author YangJun
 * @Date 2021年10月27日 09:31:39
 **/
@Service
public class ReUsingService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysPermissionService permissionService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysRoleDeptService roleDeptService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private IAsmsAssetFullInfoService assetFullInfoService;
    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    public R<LoginUser> getUserLoginInfo(SysUser sysUser) {
        // 角色集合
        List<SysUserRole> userRoles = sysUserRoleService.list(new QueryWrapper<SysUserRole>()
                .eq(SysUserRole.USER_ID, sysUser.getUserId()));
//        if(userRoles.size()==0){
//            return R.fail("你没有角色信息，请联系管理员");
//        }
        Set<Long> roleIds = new HashSet<>();
        Set<String> roles = new HashSet<>();
        List<SysRole> sysRoles = new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
            SysRole sysRole = roleService.selectRoleById(userRole.getRoleId());
            sysRoles.add(sysRole);
            roles.add(sysRole.getRoleKey());
        }
        sysUser.setRoles(sysRoles);
        sysUser.setRoleIds(roleIds.toArray(new Long[0]));
        LoginUser sysUserVo = new LoginUser();
        if (sysUser.getDeptId() != null && sysUser.getDeptId() != 0) {
            SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
            //用户当前部门的祖级部门
//            Long[] longIds = Convert.toLongArray(sysDept.getAncestors());
//            //用户顶级部门
//            Long topDeptId = sysDept.getDeptId();
//            if(longIds.length>1){
//                topDeptId=longIds[1];
//            }
            //deptIdsFromTopDept.add(0L);
            //查看用户当前部门的下级部门
//            getDeptListByTopDeptId(topDeptId).forEach(dept->{
//                deptIdsFromTopDept.add(dept.getDeptId());
//            });
            //该角色能看到的部门
            Set<Long> deptIdsFromRoles = new HashSet<>();
            //用户本身部门
            deptIdsFromRoles.add(sysDept.getDeptId());
//            List<SysDept> depts = deptService.getChildDept(sysDept.getDeptId());
//            for (SysDept dept : depts) {
//                deptIdsFromRoles.add(dept.getDeptId());
//            }

            sysUserVo.setSysDept(sysDept);
            for (SysRoleDept roleDept : roleDeptService.list(new QueryWrapper<SysRoleDept>()
                    .in(roleIds.size() > 0, SysRoleDept.ROLE_ID, roleIds))) {
                deptIdsFromRoles.add(roleDept.getDeptId());

            }
            //只是一级部门
            //deptIdsFromRoles
            List<SysDept> list = deptService.list(new QueryWrapper<SysDept>()
                    .in(deptIdsFromRoles.size() > 0, SysDept.DEPT_ID, deptIdsFromRoles)
                    .select(SysDept.DEPT_ID, SysDept.DEPT_TYPE));
            sysUserVo.setDeptIds(deptIdsFromRoles);
            Set<Long> maintenanceDeptIds = new HashSet<>();
            Set<Long> ownDeptIds = new HashSet<>();
            //角色所属部门类型（0系统管理，1售后管理部门，2资产管理部门，3物联网部门，4巡检部门，5代理商）
            for (SysDept dept : list) {
                if (dept.getDeptType().contains("1")) {
                    maintenanceDeptIds.add(dept.getDeptId());
                }
                if (dept.getDeptType().contains("2")) {
                    ownDeptIds.add(dept.getDeptId());
                }
            }
            //用户能看到的维护商部门
            sysUserVo.setUserMaintenanceDeptIds(maintenanceDeptIds);
            //用户能看到的所有方部门
            sysUserVo.setUserOwnDeptIds(ownDeptIds);
        } else {
            sysUserVo.setDeptIds(null);
            sysUserVo.setSysDept(null);
        }
        //获取该部门所在的顶级部门的所有部门，来查询该用户能获取的部门权限数组

        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());

        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setRoleIds(roleIds);
        return R.ok(sysUserVo);
    }

    public List<SysDept> getDeptListByTopDeptId(Long topDeptId) {
        return deptService.list(new QueryWrapper<SysDept>()
                .like(SysDept.ANCESTORS, "," + topDeptId + ",").or()
                .likeLeft(SysDept.ANCESTORS, "," + topDeptId).or()
                .likeRight(SysDept.ANCESTORS, topDeptId + ","));
    }


    //  @D@S("master")
    @Transactional
    public void updateFullInfo(UpdateWrapper<AsmsAssetFullInfo> updateWrapper) {
        //RootContext.bind(xid);
        assetFullInfoService.update(updateWrapper);
        //throw new GlobalException("尝试回滚");
    }

    /**
     * 获取过去多少天内的日期数组
     *
     * @param intervals intervals天内
     * @return 日期数组
     */
    public ArrayList<String> getDays(int intervals) {
        ArrayList<String> pastDaysList = new ArrayList<>();
        for (int i = intervals - 1; i >= 0; i--) {
            pastDaysList.add(getPastDate(i));
        }
        return pastDaysList;
    }

    /**
     * 获取过去第几天的日期
     *
     * @param past 第past天
     * @return 第past天的日期字符串
     */
    public String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日");
        return format.format(today);
    }

    /**
     * 获取过去多少周的日期数组
     *
     * @param intervals intervals周内
     * @return intervals周内的日期数组
     */
    public List<String> getWeeks(int intervals) {
        ArrayList<String> list = new ArrayList<>();
        for (int i = intervals; i > 0; i--) {
            list.add(getPastWeek(i));
        }
        SimpleDateFormat format = new SimpleDateFormat("yy");
        String year = format.format(new Date());
        String a = "";
        for (String s : list)
            if (s.contains("年第01周")) a = s;
        String s1 = a.replace(a, year + "年第01周");
        list.add(s1);
        list.remove(a);
        String[] array = list.toArray(new String[0]);
        Arrays.sort(array);
        return Arrays.asList(array);
    }

    /**
     * 获取过去第几周的日期字符串
     *
     * @param past 第past周
     * @return 第past周的日期字符串
     */
    public String getPastWeek(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.WEEK_OF_YEAR, -past);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yy年第ww周");
        return format.format(date);
    }

    /**
     * 获取最近一年的月份的字符串列表
     *
     * @return
     */
    public ArrayList<String> getRecentOneYearMonth() {
        ArrayList<String> list = new ArrayList<>();
        for (int i = 11; i >= 0; i--) {
            list.add(getPastMonth(i));
        }
        return list;
    }

    /**
     * 获取过去的某个月
     *
     * @param past
     * @return
     */
    public String getPastMonth(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -past);
        Date date = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yy年MM月");
        return format.format(date);
    }

    /**
     * 比较传入的两个集合的内容是否相同
     *
     * @param l1
     * @param l2
     * @return
     */
    public boolean compareListContent(List<String> l1, List<String> l2) {
        if ((l1 == null && l2 != null) || (l1 != null && l2 == null)) {
            return false;
        }
        if (l1.size() != l2.size()) {
            return false;
        }
        String[] arr1 = l1.toArray(new String[0]);
        String[] arr2 = l2.toArray(new String[0]);
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        return Arrays.equals(arr1, arr2);
    }

    /**
     * 判断用户账号在系统中的唯一性
     *
     * @param userName
     * @return true:表示用户账号已存在、false:表示用户账号
     * 不存在
     */
    public boolean userNameIsExist(String userName) {
        HashSet<String> userNameSet = new HashSet<>();
        List<SysUser> userList = userService.list();
        userList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getUserName()))
                userNameSet.add(item.getUserName());
        });
        return userNameSet.contains(userName);
    }

    /**
     * 判断用户手机号在系统中的唯一性
     *
     * @param phoneNumber
     * @return true:表示用户手机号已存在、false:表示用户手机号不
     * 存在
     */
    public boolean phoneNumberIsExist(String phoneNumber) {
        HashSet<String> phoneNumberSet = new HashSet<>();
        List<SysUser> userList = userService.list();
        userList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getPhonenumber()))
                phoneNumberSet.add(item.getPhonenumber());
        });
        return phoneNumberSet.contains(phoneNumber);
    }


    /**
     * 递归地获取钉钉根部门下的所有部门
     *
     * @param resultList
     * @param access_token
     * @return
     */
    public List<GetDingAllDeptVo.DingDept> recursionGetDingDept(List<GetDingAllDeptVo.DingDept> resultList,
                                                                String access_token) {
        RestTemplate restTemplate = restTemplateBuilder.build();
        ArrayList<GetDingAllDeptVo.DingDept> dingDepts = new ArrayList<>();
        for (GetDingAllDeptVo.DingDept dingDept : resultList) {
            String getNextDingDeptListUrl = "https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token="
                    + access_token;
            ResponseEntity<GetDingAllDeptVo> deptList = restTemplate
                    .postForEntity(getNextDingDeptListUrl, dingDept.getDept_id(), GetDingAllDeptVo.class);
            List<GetDingAllDeptVo.DingDept> result = Objects.requireNonNull(deptList.getBody()).getResult();
            if (result.size() > 0) {
                dingDepts.addAll(result);
                ReUsingService reUsingService = new ReUsingService();
                List<GetDingAllDeptVo.DingDept> dingDepts1 = reUsingService.recursionGetDingDept(result, access_token);
                if (dingDepts1.size() > 0)
                    dingDepts.addAll(dingDepts1);
            }
        }
        return dingDepts;
    }

    /**
     * 获取本月的开始时间，如2022-06-01 00:00:00
     * @return 本月第一天凌晨0点的时间戳（ms）
     */
    public Long getThisMonthStartTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis();
    }

}